package structure;

/**
 * @author or2
 * @date 2021/8/9 0:07
 */
public class UFSet implements UnionFind{

    private int[] ids;

    public UFSet(int size) {

        ids = new int[size];

        for (int i = 0; i < ids.length; i++) {
            ids[i] = i;
        }
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void Union(int p, int q) {
        int pTag = find(p);
        int qTag = find(q);
        if (pTag > qTag) {
            ids[pTag] = ids[qTag];
        } else {
            ids[qTag] = ids[pTag];
        }
    }

    /**
     * 查找当前元素所属集合标签
     * @param p 元素
     * @return 元素所属集合的标签
     */
    public int find(int p) {
        int temp = p;
        while (ids[temp] != temp) {
            temp = ids[temp];
        }
        ids[p] = temp;
        return temp;
    }

    public int getSize() {
        return ids.length;
    }
}
